chrome.bookmarks.getTree(function (bookmarkTreeNodes) {
    console.log("Bookmark Initiate");
    // 将书签数据保存至内存里
    chrome.storage.local.set({"bookmarkList": extractData(bookmarkTreeNodes)}, function () {
    });
});

// 递归提取 id, parentId, title, url 字段
function extractData(nodes) {
    let result = [];

    nodes.forEach(node => {
        if (node.id && node.title && node.url) {
            result.push({
                id: node.id,
                parentId: node.parentId,
                name: node.title,
                url: node.url
            });
        }

        // 如果有子节点，递归处理
        if (node.children) {
            result = result.concat(extractData(node.children));
        }
    });

    return result;
}

// 监听事件
chrome.bookmarks.onCreated.addListener(function (bookmarkId, bookmarkInfo) {
    console.log("Bookmark created:", JSON.stringify(bookmarkInfo));
    chrome.storage.local.get("bookmarkList", result => {
        const bookmarkList = result.bookmarkList;
        bookmarkList.push({
            id: bookmarkInfo.id,
            parentId: bookmarkInfo.parentId,
            name: bookmarkInfo.title,
            url: bookmarkInfo.url
        })
        chrome.storage.local.set({"bookmarkList": bookmarkList}, function () {
        });
    });
});

chrome.bookmarks.onRemoved.addListener(function (bookmarkId, removeInfo) {
    console.log("Bookmark removed:", JSON.stringify(removeInfo));
    chrome.storage.local.get("bookmarkList", result => {
        const bookmarkList = result.bookmarkList;
        const targetIndex = bookmarkList.findIndex(item => item.id === bookmarkId);
        if (targetIndex !== -1) {
            bookmarkList.splice(targetIndex, 1);
            chrome.storage.local.set({"bookmarkList": bookmarkList}, function () {
            });
        }
        console.log("目标位置：", targetIndex)
    });
});

chrome.bookmarks.onChanged.addListener(function (bookmarkId, changeInfo) {
    console.log("Bookmark changed:", bookmarkId, JSON.stringify(changeInfo));
    chrome.storage.local.get("bookmarkList", result => {
        let bookmarkList = result.bookmarkList;
        const targetIndex = bookmarkList.findIndex(item => item.id === bookmarkId);
        const bookmarkObj = bookmarkList[targetIndex];
        if (targetIndex !== -1) {
            bookmarkList.splice(targetIndex, 1);
            bookmarkList.push({
                id: bookmarkObj.id,
                parentId: bookmarkObj.parentId,
                name: changeInfo.title,
                url: changeInfo.url
            })
            chrome.storage.local.set({"bookmarkList": bookmarkList}, function () {
            });
        }
        console.log("目标位置：", targetIndex)
    });
});